/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lagrangeinterpolation;

import java.util.ArrayList;
import java.util.Arrays;

/**
 *
 * @author PavelsKletnojs
 */
public class Polynomial {
    private  ArrayList<Double> coefs;
    
    public Polynomial(Double... coefs){
	this.coefs = new ArrayList<Double>(coefs.length);
	this.coefs.addAll(Arrays.asList(coefs));
    }
    
    public Polynomial(ArrayList<Double> coefs){
	this.coefs = new ArrayList<Double>(coefs.size());
	for(Double coef: coefs){
	    this.coefs.add(coef);
	}
    }
    public Polynomial(){
	this.coefs = new ArrayList<Double>();
    }
    
    public Polynomial multiply(Double mult){
	Polynomial a = this;
	Polynomial b = new Polynomial();
	for(Double coef : a.coefs){
	    b.coefs.add(coef*mult);
	}
	return b;
    }
    
    public Polynomial multiply(Polynomial poly){
	Polynomial a = this;
	Polynomial b = poly;
	Polynomial c = new Polynomial();
	
	int cDegree = a.getDegree() + b.getDegree() + 1;
	for(int i = 0; i<cDegree; i++){
	    c.coefs.add(0.0);
	}
	for (int i = 0; i <= a.getDegree(); i++){
            for (int j = 0; j <= b.getDegree(); j++){
		c.coefs.set(i+j, c.coefs.get(i+j) + a.coefs.get(i) * b.coefs.get(j));
	    }
	}
	return c;
    }
    public Polynomial divide(Double denom){
	Polynomial a = this;
	Polynomial b = new Polynomial();
	for(Double coef : a.coefs){
	    b.coefs.add(coef/denom);
	}
	return b;
    }
    
    public Polynomial plus(Polynomial poly){
	Polynomial a = this;
	Polynomial b = poly;
        Polynomial c = new Polynomial();
	
	int cDegree = Math.max(a.getDegree(), b.getDegree()) + 1;
	for(int i = 0; i<cDegree; i++){
	    c.coefs.add(0.0);
	}
        for (int i = 0; i <= a.getDegree(); i++){
	    c.coefs.set(i, c.coefs.get(i) + a.coefs.get(i));
	}
        for (int i = 0; i <= b.getDegree(); i++){
	    c.coefs.set(i, c.coefs.get(i) + b.coefs.get(i));
	}
        return c;
    }
    
    public Double getFunction(double x){
	double fx = 0.0;
	for(int i = 0; i<coefs.size(); i++){
	    fx += coefs.get(i)*Math.pow(x, this.getDegree()-i);
	}
	return fx;
    }
    
    @Override
    public String toString(){
	StringBuilder poly = new StringBuilder("");
	for(int i = 0; i<this.coefs.size(); i++){
	    if(this.coefs.get(i) < 0){
		poly.append(" ");
	    }
	    else{
		poly.append(" +");
	    }
	    poly.append(this.coefs.get(i));
	    poly.append("x^");
	    poly.append(this.coefs.size()-i-1);
	}
	return poly.toString();
    }
    
    public int getDegree(){
	return coefs.size()-1;
    }
}
